<template>
  <div class="hotel-edit-container">
    <el-card class="hotel-card">
      <div class="hotel-title">
        <span>{{ isEdit ? '编辑酒店信息' : '添加新酒店' }}</span>
      </div>

      <el-row :gutter="32" class="form-row">
        <el-col :span="12">
          <el-form :model="hotelForm" :rules="rules" ref="hotelForm" label-width="120px">


            <el-form-item label="酒店名称" prop="hotelName">
              <el-input v-model="hotelForm.hotelName" />
            </el-form-item>

            <el-form-item label="最低价格" prop="minimumPrice">
              <el-input-number v-model="hotelForm.minimumPrice" :min="0" />
            </el-form-item>

            <el-form-item label="酒店地址" prop="hotelAddress">
              <el-input v-model="hotelForm.hotelAddress" />
            </el-form-item>

            <el-form-item label="景点名称" prop="scenicAreaName">
              <el-select v-model="hotelForm.scenicAreaName" filterable placeholder="请选择景点" @change="handleScenicChange">
                <el-option v-for="spot in scenicSpots" :key="spot.scenicSpotId" :label="spot.scenicAreaName"
                  :value="spot.scenicAreaName" />
              </el-select>
            </el-form-item>

            <el-form-item label="省份" prop="province">
              <el-input v-model="hotelForm.province" />
            </el-form-item>

            <el-form-item label="城市" prop="city">
              <el-input v-model="hotelForm.city" />
            </el-form-item>

            <el-form-item label="酒店链接" prop="hotelLinks">
              <el-input v-model="hotelForm.hotelLinks" />
            </el-form-item>

            <el-form-item label="更新时间" v-if="isEdit">
              <el-date-picker v-model="hotelForm.updateTime" type="datetime" disabled placeholder="选择日期时间" />
            </el-form-item>
          </el-form>
        </el-col>

        <el-col :span="12" class="image-col">
          <div class="image-section">
            <span class="image-label">酒店图片：</span>

            <!-- 修改后的九宫格，用于显示上传的图片 -->
            <div class="image-grid">
              <div v-for="(img, index) in hotelImages" :key="index" class="grid-item">
                <el-image :src="img" :preview-src-list="[img]" fit="cover" class="grid-image" />
                <div class="grid-item-actions">
                  <el-button type="danger" size="mini" @click="handleDeleteImage(img)">删除</el-button>
                  <el-upload action="http://localhost:8080/api/updateHotelImage" :show-file-list="false"
                    :on-success="loadHotelImages" :before-upload="beforeUpload"
                    :data="{ hotelId: hotelForm.hotelId, oldImageUrl: img }">
                    <el-button size="mini">修改</el-button>
                  </el-upload>
                </div>
              </div>

              <!-- 空白占位符，用Plus图标代替"位置i"文字 -->
              <div v-for="i in 9 - hotelImages.length" :key="'empty-' + i" class="grid-item empty-placeholder">
                <!-- 修改这里：直接使用el-upload的默认触发行为，不再手动触发 -->
                <el-upload class="plus-upload" action="http://localhost:8080/api/uploadHotelImage" :show-file-list="false"
                  :on-success="handleUploadSuccess" :before-upload="beforeUpload"
                  :data="{ hotelId: hotelForm.hotelId || 0 }">
                  <el-icon class="placeholder-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <div class="button-group">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { Upload, Plus } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  components: { Upload, Plus },
  props: {
    id: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      isEdit: false,
      regionOptions: [],
      hotelForm: {
        hotelId: null,
        hotelName: '',
        minimumPrice: 0,
        hotelAddress: '',
        scenicAreaName: '',
        province: '',
        city: '',
        hotelLinks: '',
        updateTime: '',
      },
      rules: {
        hotelId: [{ required: true, message: '请输入酒店ID', trigger: 'blur' }],
        hotelName: [{ required: true, message: '请输入酒店名称', trigger: 'blur' }],
        minimumPrice: [{ required: true, message: '请输入最低价格', trigger: 'blur' }],
        hotelAddress: [{ required: true, message: '请输入酒店地址', trigger: 'blur' }],
        scenicAreaName: [{ required: true, message: '请选择景点', trigger: 'change' }],
        province: [{ required: true, message: '请输入省份', trigger: 'blur' }],
        city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
        hotelLinks: [{ required: true, message: '请输入酒店链接', trigger: 'blur' }]
      },
      scenicSpots: [],
      hotelImages: [],
      canUploadImage: false
    }
  },
  created() {
    const id = this.$route.query.id
    if (id) {
      this.isEdit = true
      this.loadHotelData(id)
      this.loadHotelImages(id)
      this.canUploadImage = true
    } else {
      // 新增时自动生成 hotelId
      this.generateHotelId()
    }
    this.loadScenicSpots()
    this.loadRegionOptions()
  },
  methods: {
    generateHotelId() {
      axios.get('http://localhost:8080/mw/hotelList').then(res => {
        const hotels = res.data || []
        const maxId = hotels.length > 0 ? Math.max(...hotels.map(h => h.hotel_id)) : 0
        this.hotelForm.hotelId = maxId + 1
      })
    },
    loadScenicSpots() {
      axios.get('http://localhost:8080/mw/ScenicSpotList').then(res => {
        this.scenicSpots = res.data
      })
    },
    loadHotelData(id) {
      axios.get(`http://localhost:8080/mw/hotelById?id=${id}`).then(res => {
        const data = res.data
        this.hotelForm = {
          hotelId: data.hotel_id,
          hotelName: data.hotel_name,
          minimumPrice: data.minimum_price,
          hotelAddress: data.hotel_address,
          scenicAreaName: data.scenic_area_name,
          province: data.province,
          city: data.city,
          hotelLinks: data.hotel_links,
          updateTime: data.update_time
        }
      })
    },
    // 修复此方法中的模板字符串错误
    loadHotelDataFixed(id) {
      axios.get(`http://localhost:8080/mw/hotelById?id=${id}`).then(res => {
        const data = res.data
        this.hotelForm = {
          hotelId: data.hotel_id,
          hotelName: data.hotel_name,
          minimumPrice: data.minimum_price,
          hotelAddress: data.hotel_address,
          scenicAreaName: data.scenic_area_name,
          province: data.province,
          city: data.city,
          hotelLinks: data.hotel_links,
          updateTime: data.update_time
        }
      })
    },
    loadHotelImages(hotelId) {
      const id = hotelId || this.hotelForm.hotelId
      if (!id) return
      axios.get(`http://localhost:8080/api/hotelImages?hotelId=${id}`).then(res => {
        this.hotelImages = res.data || []
      })
    },
    // 修复此方法中的模板字符串错误
    loadHotelImagesFixed(hotelId) {
      const id = hotelId || this.hotelForm.hotelId
      if (!id) return
      axios.get(`http://localhost:8080/api/hotelImages?hotelId=${id}`).then(res => {
        this.hotelImages = res.data || []
      })
    },
    handleScenicChange(val) {
      const selectedSpot = this.scenicSpots.find(spot => spot.scenicAreaName === val)
      if (selectedSpot) {
        const region = this.regionOptions.find(r => r.region_id === selectedSpot.regionId)
        if (region) {
          this.hotelForm.province = region.province
          this.hotelForm.city = region.city
        } else {
          this.hotelForm.province = ''
          this.hotelForm.city = ''
        }
      }
    },
    beforeUpload(file) {
      // 新增：未保存酒店不能上传图片
      if (!this.canUploadImage) {
        this.$message.error('请先添加酒店信息保存后再上传')
        return false
      }
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.error('只能上传图片文件！')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2MB！')
      }
      return isImage && isLt2M
    },
    // 修改上传成功处理函数
    handleUploadSuccess(response) {
      if (response.success) {
        this.$message.success('图片上传成功')
        // 假设响应中有图片的 URL，我们将其添加到 hotelImages 数组
        this.hotelImages.push(response.imageUrl)  // 假设 response.imageUrl 是图片的 URL
        this.loadHotelImages()  // 刷新已上传的图片
      } else {
        this.$message.error(response.msg || '图片上传失败')
      }
    },
    // 修复此方法中的模板字符串错误
    handleUploadSuccessFixed(response) {
      if (response.success) {
        this.$message.success('图片上传成功')
        // 重新加载图片列表
        this.loadHotelImages(this.hotelForm.hotelId)
      } else {
        this.$message.error(response.msg || '图片上传失败')
      }
    },
    handleDeleteImage(imageUrl) {
      axios.delete('http://localhost:8080/api/hotelImage', {
        params: {
          hotelId: this.hotelForm.hotelId,
          imageUrl
        }
      }).then(res => {
        if (res.data.success) {
          this.$message.success('图片删除成功')
          this.loadHotelImages(this.hotelForm.hotelId)
        } else {
          this.$message.error(res.data.msg || '图片删除失败')
        }
      })
    },
    loadRegionOptions() {
      axios.get('http://localhost:8080/api/regions').then(res => {
        this.regionOptions = (res.data || []).map(item => ({
          region_id: item.regionID,
          province: item.province,
          city: item.city
        }))
      })
    },
    submitForm() {
      this.$refs.hotelForm.validate(valid => {
        if (valid) {
          if (!this.hotelForm.hotelId) {
            this.$message.error('酒店ID不能为空')
            return
          }
          const spot = this.scenicSpots.find(
            item => item.scenicAreaName === this.hotelForm.scenicAreaName
          )
          if (!spot) {
            this.$message.error('请选择有效的景点')
            return
          }
          const region = this.regionOptions.find(r => r.region_id === spot.regionId)
          if (!region) {
            this.$message.error('景点未关联有效地区')
            return
          }
          const submitData = {
            hotel_id: this.hotelForm.hotelId,
            hotel_name: this.hotelForm.hotelName,
            region_id: spot.regionId,
            hotel_address: this.hotelForm.hotelAddress,
            minimum_price: this.hotelForm.minimumPrice,
            scenic_spot_id: spot.scenicSpotId,
            hotel_links: this.hotelForm.hotelLinks,
            update_time: this.hotelForm.updateTime
          }
          if (!submitData.region_id || !submitData.scenic_spot_id) {
            this.$message.error('地区或景点信息不完整')
            return
          }
          const url = this.isEdit
            ? 'http://localhost:8080/mw/updateHotel'
            : 'http://localhost:8080/mw/addHotel'
          axios.post(url, submitData)
            .then(() => {
              this.$message.success(this.isEdit ? '修改成功' : '添加成功')
              // 新增：添加成功后不返回列表，允许上传图片
              this.isEdit = true
              this.canUploadImage = true
              this.loadHotelImages(this.hotelForm.hotelId)
            })
            .catch(() => {
              this.$message.error(this.isEdit ? '修改失败' : '添加失败')
            })
        }
      })
    },
    goBack() {
      this.$router.push('/hotel/list')
    }
    // 移除triggerPlusUpload方法，不再需要
  }
}
</script>


<style scoped>
.hotel-edit-container {
  padding: 32px;
  background: #f7f8fa;
  min-height: 100vh;
}

.hotel-card {
  max-width: 1100px;
  width: 100%;
  margin: 0 auto;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 4px 24px #e6e6e6;
}

.hotel-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 24px;
  color: #333;
  text-align: center;
}

.form-row {
  margin-bottom: 24px;
}

.image-col {
  display: flex;
  flex-direction: column;
}

.image-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-label {
  display: block;
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
  width: 100%;
}

.image-preview {
  width: 100%;
  height: 300px;
  margin-bottom: 16px;
  border: 1px dashed #ddd;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #c0c4cc;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 32px;
}

/* 上传按钮样式 */
.upload-button {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  transition: all 0.3s;
}

.upload-button:hover {
  background-color: #66b1ff;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.upload-icon {
  font-size: 16px;
  margin-right: 6px;
}

/* 新的九宫格样式 - 用于显示图片 */
.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  /* 3列 */
  grid-gap: 16px;
  /* 网格间距 */
  margin-top: 20px;
  /* 与上方按钮的间距 */
  width: 100%;
}

.grid-item {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 10px;
  min-height: 150px;
  /* 最小高度 */
  cursor: pointer;
  transition: all 0.3s;
  border: 1px dashed #dcdfe6;
}

.grid-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 8px;
}

.grid-item-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.empty-placeholder {
  border-style: dashed;
  background-color: #fafafa;
}

.placeholder-icon {
  font-size: 24px;
  color: #909399;
  margin-bottom: 8px;
  cursor: pointer; /* 添加指针样式，表明可点击 */
}

/* 为Plus上传组件添加样式 */
.plus-upload {
  display: contents; /* 让子元素直接成为网格项的子元素 */
}
</style>